package com.LeeCode;

/**
 * 每种字符至少取 K 个
 */

public class Code2516 {
    public static void main(String[] args) {
        String s = "aabaaaacaabc";
        int k = 2;
        System.out.println(new Code2516().takeCharacters(s, k));
    }

    public int takeCharacters(String s, int k) {
        int[] target = new int[3];
        char[] chars = s.toCharArray();

        for (char c : chars) {
            target[c - 'a']++;
        }
        if (target[0] < k || target[1] < k || target[2] < k) {
            return -1;
        }

        int ans = 0, left = 0;
        int[] cnt = new int[3];

        for (int i = 0; i < chars.length; i++) {
            cnt[chars[i] - 'a']++;

            while (cnt[0] > target[0] - k || cnt[1] > target[1] - k || cnt[2] > target[2] - k) {
                cnt[chars[left] - 'a']--;
                left++;
            }

            ans = Math.max(ans, i - left + 1);
        }

        return chars.length - ans;
    }
}
